//
//  BLEVC.m
//  UHealth
//
//  Created by gjtxz on 14/12/30.
//  Copyright (c) 2014年 gjtx. All rights reserved.
//

#import "BLEVC.h"
#import "BlueToothManager.h"
#import "DBManage.h"
#import "LogDataObj.h"
#import "BodyTemperatureObj.h"
#import "MBProgressHUD+YCL.h"
#import "Model.h"
#import "NSString+BloodSugar.h"
//#import "FamilyCell.h"

#import "NavView.h"

#import "PersonalVC.h"
#import "UserObj.h"
#import "UIImageView+WebCache.h"

#import "iToast.h"
#import "AddUserVC.h"
#import "AFNetworking.h"


/** BLE 协议 */
// 体温整数位: 数值小于等于50，则更新；数值大于50，则保持上一次数值
#define kBLETemHightByte    9

// 体温小数位: 数值小于100，则更新；数值大于等于100，则保持上一次数值
#define kBLETemLowByte      8

// 接触状态: 未接触-0xff; 已接触-0x00;
#define kBLEStateByte       6

// 电压状态: 电压正常-0xff; 低电压-0x00;
#define kBLEPower           7

// 版本号:
#define kBLEVerMainByte     23
#define kBLEVerSubByte      24


#define kSelfWidth 250
#define kHeaderHeight 50
#define kMargin 14

// 日志状态
typedef NS_ENUM(int, BLELogType) {
    BLELogTypeHeightTemperature = 1 << 0,
    BLELogTypeDisconnected      = 1 << 1,
    BLELogTypeConnected         = 1 << 2,
    BLELogTypeLowPower          = 1 << 3,
};



@interface BLEVC ()<UITableViewDataSource,UITableViewDelegate, CBPeripheralDelegate>

/** 成员列表 */
@property (nonatomic, weak  ) UITableView    *tableView;

/** 扫描按钮 */
@property (nonatomic, weak  ) UIButton       *scanButton;

//@property (nonatomic, strong) NSMutableArray *familyArr;
@property (nonatomic, strong) NSMutableArray *peripheals;

/** 用户 */
@property (nonatomic, strong) UserObj *user;

/** icon */
@property (nonatomic, weak) UIImageView *icon;
/** nameLabel */
@property (nonatomic, weak) UILabel *nameLabel;

@property (nonatomic, strong) NSTimer        *timer;

@property (nonatomic        ) NSInteger      cantGetDataTimes;
@property (nonatomic        ) NSInteger      invalidTouchCount;

/** 上一次数据 */
@property (nonatomic, assign) float previousValue;
/** 接触状态 */
@property (nonatomic, assign, getter=isTouched) int touched;


/** 最后一次连接状态 */
@property (nonatomic, assign, getter=isLastConnected) BOOL lastConnected;

/** 当前选中的设备 */
@property (nonatomic, strong) CBPeripheral   *currenPperipheal;

/** 扫描到的所有蓝牙 */
@property (nonatomic, strong) NSMutableArray *allPeripheals;


/** 日志状态 */
@property (nonatomic, assign) BLELogType logType;
@end

@implementation BLEVC

#pragma mark -
#pragma mark Getter && Setter

- (NSMutableArray *)peripheals {
    if (!_peripheals) {
        _peripheals = [NSMutableArray array];
    }
    return _peripheals;
}


#pragma mark -
#pragma mark 视图
- (void)viewDidLoad {
    [super viewDidLoad];
    
    //视图
    
    UIView *aContentView = [[UIView alloc]initWithFrame:CGRectMake(WIDTH - kSelfWidth, 0, kSelfWidth, HEIGHT)];
    

    // 蓝牙
    UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 20, kSelfWidth, HEIGHT-20)];
    tableView.dataSource = self;
    tableView.delegate = self;
    tableView.backgroundColor = [UIColor clearColor];
    tableView.backgroundView = nil;
    tableView.tableFooterView = [[UIView alloc] init];//不显示下面的分割线
    [tableView setSeparatorInset:UIEdgeInsetsZero];
    //    [tableView registerNib:[UINib nibWithNibName:NSStringFromClass([FamilyCell class]) bundle:[NSBundle mainBundle]] forCellReuseIdentifier:NSStringFromClass([FamilyCell class])];
    [aContentView addSubview:tableView];
    self.tableView = tableView;
    
    // 扫描按钮
    UIButton *scanButton = [UIButton buttonWithType:UIButtonTypeCustom];
    scanButton.frame = CGRectMake(50, HEIGHT - 35-20, kSelfWidth - 100, 35);
    [scanButton setTitle:kLocal(@"search_device") forState:UIControlStateNormal];
    [scanButton setTitle:kLocal(@"searching") forState:UIControlStateDisabled];
    [scanButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [scanButton setImage:[UIImage imageNamed:@"search"] forState:UIControlStateNormal];
    [scanButton addTarget:self action:@selector(scanButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    scanButton.tag = 1;
    [scanButton.layer setMasksToBounds:YES];
    [scanButton.layer setCornerRadius:10.0];//设置矩形是个圆角半径
    [scanButton.layer setBorderWidth:1.0];//边框宽度
    [scanButton.layer setBorderColor:[[UIColor whiteColor]CGColor]];
    //    scanButton.hidden =!self.isBLE;
    [aContentView addSubview:scanButton];
    self.scanButton = scanButton;
    
    
//    [self performSelector:@selector(scanButtonClicked:) withObject:nil afterDelay:1];
    
    [self setContentViewInSideBar:aContentView];
    
    [[DBManage sharedManager] setValue:[[UserObj alloc]init] forKey:kFirstUser];
    [[DBManage sharedManager] addObserver:self forKeyPath:kFirstUser options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL];
}

-(void)dealloc{
    [[DBManage sharedManager] removeObserver:self forKeyPath:kFirstUser];
}


#pragma mark - KVO 回调
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
//    if([keyPath isEqualToString:kFirstUser])
//    {//用户ID为0 的用户
//        [self addUserBlock:0 andIsDel:NO];
//    }
    
    if([keyPath isEqualToString:kFirstUser])
    {
        [_tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationAutomatic];
    }
}



-(void)addUserBlock:(int )famID andIsDel:(BOOL)isDel
{
    
    if (famID == kGetFamID) {
        if (isDel) {//把默认用户删除了 用户0变为默认用户
            NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
            [def setInteger:0 forKey:kLastFamID];
            [def synchronize];
        }else{//更新默认用户资料时，检测是否变更了默认用户头像
            
        }
        if (_block) {//主界面更新
            _block([[DBManage sharedManager] getDefUser].headImg);
        }
    }

}


// 扫描蓝牙
-(void)scanButtonClicked:(UIButton *)btn
{
    // 扫描过程，禁用按钮
    btn.enabled = NO;
    [self.peripheals removeAllObjects];
    // 每次点击扫描按钮，只扫描 2 秒
    
    MBProgressHUD *hud = [MBProgressHUD showWhileExecuting:@"正在扫描设备..."];
    
    [[BlueToothManager sharedManager] scanForPeripheralsByInterval:2 completion:^(NSArray *peripherals, NSArray *advertisementDataArray, NSArray *dateArray) {
        
        // 扫描完成，启用按钮
        btn.enabled = YES;
        [hud hide:YES];
        
        if (peripherals.count>0) {
            [MBProgressHUD showSuccess:kLocal(@"scan_complete")];
            // 保存扫描到的蓝牙设备
            [self.peripheals addObjectsFromArray:peripherals];
            kDebug(@"扫描的的设备：\n%@", self.peripheals);
            [self.tableView reloadData];
        } else {
            [MBProgressHUD showError:kLocal(@"scan_again")];
        }
    }];
    
}

// 停止计时
- (void)invalidTimer:(NSString *)reason
{
    if (self.timer) {
        if ([self.timer isValid]) {
            [self.timer invalidate];
            if (reason) {
                kDebug(@"停止计时, 原因：%@", reason);
            }
            
        }
        self.timer = nil;
    }
}


// 获取一次体温数据 （扫描1s，查找选中的蓝牙，取出数据）
- (void)scanForTemperatureWithIdentifier
{
    // 扫描 2秒
    [[BlueToothManager sharedManager] scanForPeripheralsByInterval:2 completion:^(NSArray *peripherals, NSArray *advertisementDataArray, NSArray *dateArray) {
        
        BOOL connectToDevice = NO;
        self.lastConnected = NO;
        
        NSDictionary *advertisementData = nil;
        NSDate *dataDate = nil;
        
        
        // 1. 遍历扫描结果，确定连接状态
        for (NSInteger i = 0; i < peripherals.count; i++) {
            CBPeripheral *peripheral = peripherals[i];
            if ([[peripheral.identifier UUIDString] isEqualToString:[self.currenPperipheal.identifier UUIDString]]) {
                
                // 扫描到，就认为连接上
                connectToDevice = YES;
                
                // 隐藏侧边栏
                [self dismissAnimated:YES];
                
                // 取出对应的广告数据
                advertisementData = advertisementDataArray[i];
                // 扫描到的时间
                dataDate = dateArray[i];
                break; // 扫描到第一个即可
            } else {
                // 没扫到，就认为断开连接
                connectToDevice = NO;
            }
        }
        
        // 2. 处理连接状态
        if (connectToDevice) {
            
            // 日志: 连接成功
            self.logType = BLELogTypeConnected;
            // 插入日志
            [self insertLogDataWithType:self.logType];

            // 获取设备温度
            Byte *bytes = (Byte *)[(NSData *)(advertisementData[@"kCBAdvDataManufacturerData"]) bytes];
            if (!bytes) {
                [MBProgressHUD showError:kLocal(@"please_reselect")];
                [self invalidTimer:kLocal(@"device_not_match")];
                self.currenPperipheal = nil;
                self.cantGetDataTimes = 0;
                return ;
            }
            
//            for (int i = 0; i <=4; i++) {
//                kDebug(@"ID %d = %d", i, bytes[i]);
//            }
            
            float temperatureValue = bytes[kBLETemHightByte] + bytes[kBLETemLowByte]*0.01;
            
            // 接触状态
            int stateValue = bytes[kBLEStateByte];
            
            // 体温
            int hight = bytes[kBLETemHightByte];
            int low = bytes[kBLETemLowByte];
            
            // 低电压
            int power = bytes[kBLEPower];
            
            // 版本号
            int mainVer = bytes[kBLEVerMainByte];
            int subVer = bytes[kBLEVerSubByte];
            
            if (power == 0) { // 日志: 电量低
                self.logType = BLELogTypeLowPower;
                // 插入日志
                [self insertLogDataWithType:self.logType];
            }
            
            kDebug(@"state: %d, 低电压: %d, 整数位: %d, 小数位: %d, 版本号: %d.%d", stateValue, power, hight, low, mainVer, subVer);
            

            // 处理接触状态
            if (stateValue == 0) {
                if (temperatureValue < 50) {
                    self.previousValue = temperatureValue;
                    // 先归零无效接触次数
                    self.invalidTouchCount = 0;
                }
                kDebug(@"接触良好，体温值:%.1f，测试ID = %@",temperatureValue, [Model sharedModel].currentMeasureIdentifier);
                
            }
            
            kDebug(@"上一次温度： %.1f", self.previousValue);
            
            if (temperatureValue > 100) {
                // 使用上一次温度
                temperatureValue = self.previousValue;

                // 温度过高，说明没有接触设备
                self.invalidTouchCount++;
                
                #warning 设备发送未接触消息需要等30秒，此次无需累计
                if (self.invalidTouchCount >= 1) {
                    // 三次没接触好，更换测量标识
                    [Model sharedModel].currentMeasureIdentifier = [NSString dateStampString:nil];
                    self.touched = 1;
                    kDebug(@"未接触设备");
                }
                kDebug(@"未接触好，第%ld次，测试ID = %@", (long)self.invalidTouchCount, [Model sharedModel].currentMeasureIdentifier);
            }
            
            if (temperatureValue > 0) {
                // 传出 温度 - 状态
                self.updateBlock(temperatureValue, self.isTouched);
            }
            
            
            
            // 插入温度数据
            [self insertDataWithTemperatureValue:temperatureValue date:dataDate];

            self.cantGetDataTimes = 0;
            
            // 通知，设备连接
            //            [[NSNotificationCenter defaultCenter] postNotificationName:@"kDeviceConnected" object:nil];
        }
        else {
            
            
            self.cantGetDataTimes ++;
            kDebug(@"------ 未扫描到，第%ld次", (long)self.cantGetDataTimes);
            
            [MBProgressHUD showError:kLocal(@"did_not_scan_device")];
            
            if (self.cantGetDataTimes >= 10) {  // 连续10次扫描不到选中设备，停止扫描
                [MBProgressHUD showError:kLocal(@"bluetooth_disconnect")];
                self.currenPperipheal = nil;
                self.cantGetDataTimes = 0;
                // 停止计时
                [self invalidTimer:kLocal(@"cannot_connect")];
                
                // 日志: 断开连接
                self.logType = BLELogTypeDisconnected;
                // 插入日志
                [self insertLogDataWithType:self.logType];
                
                // 通知，设备断开
                [[NSNotificationCenter defaultCenter] postNotificationName:@"kDeviceLostConnect" object:nil];
            }
        }
        
        
    }];
}

// 保存日志
- (void)insertLogDataWithType:(int)type {
    
    // 默认用户
    UserObj *user = [[DBManage sharedManager] getDefUser];
    
    // 存储日志
    LogDataObj *log = [[LogDataObj alloc]init];
    log.userID = user.userID;
    log.deviceID = kLastBindDevice;
    log.logType = type;
    log.logDate = [NSString stringFromDate:[NSDate date]];
    
    [[DBManage sharedManager] insertData:log andTable:kLogTable];
}


// 保存温度数据
- (void)insertDataWithTemperatureValue:(float)temperatureValue date:(NSDate *)date
{
    // 默认用户
    UserObj *user = [[DBManage sharedManager] getDefUser];
    
    BodyTemperatureObj *obj  = [[BodyTemperatureObj alloc] init];
    obj.bodyTemperatureId    = 0;
    obj.userId               = user.userID;
    obj.userName             = user.name;
    obj.measureDate          = [NSDate date];
    obj.bodyTemperatureValue = temperatureValue;
    obj.isUploaded           = 0;
    if ([Model sharedModel].currentMeasureIdentifier.length <= 0) {
        [Model sharedModel].currentMeasureIdentifier = [NSString dateStampString:nil];
    }
    obj.measureIdentifier = [Model sharedModel].currentMeasureIdentifier;
    [[DBManage sharedManager] insertData:obj andTable:kTemperatureTable];
}


#pragma mark - UITableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.peripheals.count+2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) { // 用户信息
        static NSString *ID = @"UserCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
        if(!cell){
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
        }
        
        // 默认用户
        UserObj *user = [[DBManage sharedManager] getDefUser];
        [cell.imageView sd_setImageWithURL:[NSURL URLWithString:user.headImg] placeholderImage:[UIImage imageNamed:@"user"]];
        cell.textLabel.text = user.name;
        cell.imageView.layer.cornerRadius = 30;
        cell.imageView.layer.masksToBounds = YES;
        cell.backgroundColor = [UIColor clearColor];
        cell.textLabel.textColor = [UIColor whiteColor];
        
        return cell;
    } else {
        static NSString *ID = @"PeriphealCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
        if(!cell){
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
        }
        if (indexPath.row == 1) {
            cell.textLabel.text = kLocal(@"last_bind");
            cell.textLabel.font = [UIFont systemFontOfSize:12];
            NSString *lastName = [[NSUserDefaults standardUserDefaults] objectForKey:@"LastBindDevice"];
            if (!lastName) {
                lastName = kLocal(@"not_bind_yet");
            }
            cell.detailTextLabel.text = lastName;
            cell.detailTextLabel.font = [UIFont systemFontOfSize:17];
            cell.detailTextLabel.textColor = [UIColor whiteColor];
        }else{
            // 蓝牙设备
            CBPeripheral *peri = self.peripheals[indexPath.row - 2];
            cell.textLabel.text = peri.name;
            cell.detailTextLabel.text = [peri.identifier UUIDString];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
        cell.textLabel.textColor = [UIColor whiteColor];
        cell.backgroundColor = [UIColor clearColor];
        return cell;
    }
}


// 选中蓝牙
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    //点击完毕，立即恢复颜色
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    // 点击用户cell
    if (0 == indexPath.row) {
        return;
    }
    
    // 上次绑定的设备
    if (1 == indexPath.row) {
        return;
    }
    
    // 记录选中蓝牙
    self.currenPperipheal = self.peripheals[indexPath.row-2];
    
//    [[tableView cellForRowAtIndexPath:indexPath] setAccessoryType:UITableViewCellAccessoryCheckmark];
    
    // 记录最后连接设备名称
    [[NSUserDefaults standardUserDefaults] setObject:self.currenPperipheal.name forKey:@"LastBindDevice"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    
    // 停止计时
    [self invalidTimer:kLocal(@"after_select")];
    // 先扫描一下温度
    [self scanForTemperatureWithIdentifier];
    
    // 每隔 10s 再扫描一次
    self.timer = [NSTimer timerWithTimeInterval:10
                                         target:self
                                       selector:@selector(scanForTemperatureWithIdentifier)
                                       userInfo:nil
                                        repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

@end
